package com.wyp.controller.student;

import com.wyp.pojo.Scores;
import com.wyp.service.impl.QuestionsServiceImpl;
import com.wyp.service.impl.ScoresServiceImpl;
import com.wyp.service.impl.TestpapersServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("/student")
public class ExamController {

    //随机数种子
    private long randomnessSeed = System.currentTimeMillis() ^ (long) this.hashCode();
    private Random sourceOfRandomness = new Random(randomnessSeed);

    @Autowired
    private ScoresServiceImpl scoresService;

    @Autowired
    private QuestionsServiceImpl questionsService;

    @Autowired
    private TestpapersServiceImpl testpapersService;

    @RequestMapping("/exam.html/{id}")
    public String tologin(
            @PathVariable("id") int testpaperid,
            Model model,
            HttpSession session
    ) {
        Map<String, Object> examinees = (Map<String, Object>) session.getAttribute("examinee");
        Map<String, Object> testpapers = testpapersService.qureyTestpapersByid(testpaperid);
        List<Map<String, Object>> exam;
        List<Map<String, Object>> Squestions = new ArrayList<>(); //单选题
        List<Map<String, Object>> Mquestions = new ArrayList<>(); //多选题
        List<Map<String, Object>> Jquestions = new ArrayList<>(); //判断题
//        第一次考试会定下该考生考该试卷的题目，为避免考生刷新页面重复刷题，第二次进入考试页面时考生将直接回答第一次试卷的内容
        if (scoresService.qureyScoresByRepeat((int)examinees.get("stuid"), testpaperid) == null) {
            Scores scores = new Scores();
            scores.setApartmentid((int)examinees.get("apartmentid"));
            scores.setStuid((int)examinees.get("stuid"));
            scores.setTestpaperid(testpaperid);
            if (!(Boolean) testpapers.get("type")) {
                String testpapercontent = "";
                int point = 0;
                List<Map<String, Object>> Fquestions = new ArrayList<>();
                Squestions = getquestionsbytype((int)testpapers.get("singlenum"), 1, (int)testpapers.get("apartmentid"));
                Mquestions = getquestionsbytype((int)testpapers.get("multiplenum"), 2, (int)testpapers.get("apartmentid"));
                Jquestions = getquestionsbytype((int)testpapers.get("judgenum"), 3, (int)testpapers.get("apartmentid"));
                Fquestions.addAll(Squestions);
                Fquestions.addAll(Mquestions);
                Fquestions.addAll(Jquestions);
                for (Map<String, Object> question : Fquestions) {
                    if (testpapercontent.equals("")) {
                        testpapercontent = "" + (int)question.get("questionid");
                    } else {
                        testpapercontent = testpapercontent + "," + (int)question.get("questionid");
                    }
                    point = point + (int)question.get("point");
                }
                scores.setTestpapercontent(testpapercontent);
                scores.setTotalscore(point);
                scoresService.addScores(scores);
                model.addAttribute("testpaper", testpapers);
                model.addAttribute("Squestions", Squestions);
                model.addAttribute("Mquestions", Mquestions);
                model.addAttribute("Jquestions", Jquestions);
            } else {
                scores.setTestpapercontent((String)testpapers.get("testpapercontent"));
                scores.setTotalscore((int)testpapers.get("totalpoint"));
                String content = (String)testpapers.get("testpapercontent");
                String[] questionsid = content.split(",");
                for (String questionid : questionsid) {
                    if (!questionid.equals("")) {
                        Map<String, Object> question = questionsService.qureyQuestionsByid(Integer.parseInt(questionid));
                        if ((int)question.get("type") == 1) {
                            Squestions.add(question);
                        }
                        if ((int)question.get("type") == 2) {
                            Mquestions.add(question);
                        }
                        if ((int)question.get("type") == 3) {
                            Jquestions.add(question);
                        }
                    }
                }
                scoresService.addScores(scores);
                model.addAttribute("testpaper", testpapers);
                model.addAttribute("Squestions", Squestions);
                model.addAttribute("Mquestions", Mquestions);
                model.addAttribute("Jquestions", Jquestions);
            }
        } else {
            if (scoresService.qureyScoresByRepeat((int)examinees.get("stuid"), testpaperid).getReachtime() != null) {
                return "redirect:/student/notfinishexam.html";
            }
            String content = scoresService.qureyScoresByRepeat((int)examinees.get("stuid"), testpaperid).getTestpapercontent();
            String[] questionsid = content.split(",");
            for (String questionid : questionsid) {
                if (!questionid.equals("")) {
                    Map<String, Object> question = questionsService.qureyQuestionsByid(Integer.parseInt(questionid));
                    if ((int)question.get("type") == 1) {
                        Squestions.add(question);
                    }
                    if ((int)question.get("type") == 2) {
                        Mquestions.add(question);
                    }
                    if ((int)question.get("type") == 3) {
                        Jquestions.add(question);
                    }
                }
            }
            model.addAttribute("testpaper", testpapers);
            model.addAttribute("Squestions", Squestions);
            model.addAttribute("Mquestions", Mquestions);
            model.addAttribute("Jquestions", Jquestions);
        }
        return "student/exam";
    }

    private List<Map<String, Object>> getquestionsbytype(int questionnum, int type, int apartmentid) {
        List<Map<String, Object>> Aquestions = questionsService.qureyQuestionsByType(type, apartmentid);
        Collections.shuffle(Aquestions, this.sourceOfRandomness);
        return Aquestions.subList(0, questionnum);
    }

    @PostMapping("/reachresult.html")
    public String reachresult(//@RequestParam Map<String, String[]> map,
                              HttpServletRequest httpServletRequest,
                              @RequestParam("testpaperid") int testpaperid,
                              Model model,
                              HttpSession session

    ) {
        Map<String, String[]> map = httpServletRequest.getParameterMap();
        Map<String, Object> examinees = (Map<String, Object>) session.getAttribute("examinee");
        Scores scores = scoresService.qureyScoresByRepeat((int)examinees.get("stuid"), testpaperid);
        Map<String, Object> testpapers = testpapersService.qureyTestpapersByid(testpaperid);
        Map<String, Object> questions = new HashMap<String, Object>();
        List<Map<String, Object>> S = new ArrayList<>();
        List<Map<String, Object>> M = new ArrayList<>();
        List<Map<String, Object>> J = new ArrayList<>();
        String testcontent = scores.getTestpapercontent();
        String[] questionsid = testcontent.split(",");
        for (String questionid : questionsid) {
            if (!questionid.equals("")) {
                Map<String, Object> question = questionsService.qureyQuestionsByid(Integer.parseInt(questionid));
                if ((int)question.get("type") == 1) {
                    S.add(question);
                }
                if ((int)question.get("type") == 2) {
                    M.add(question);
                }
                if ((int)question.get("type") == 3) {
                    J.add(question);
                }
            }
        }

        int sn = 0, mn = 0, jn = 0;
        boolean mf = false, jf = false;
        int n = 1;
        String Sanswer = ""; //单选题答案
        String Manswer = ""; //多选题答案
        String Janswer = ""; //判断题答案
        int point = 0;
        Set<String> keySet = map.keySet();
        Iterator<String> it = keySet.iterator();
        it.next();
        while (it.hasNext()) {
            String key = it.next();
            String value = "";
            for (String s : map.get(key)) {
                value += s;
            }
            if (key.equals("check")) {
                questions.put("questionid",-1);
            } else {
                questions = questionsService.qureyQuestionsByid(Integer.parseInt(key));
            }
            if (n <= (int)testpapers.get("singlenum")) {
                for (; sn < (int)testpapers.get("singlenum"); ) {
                    if ((int)questions.get("questionid") == (int)S.get(sn).get("questionid")) {
                        if (((String)questions.get("answer")).equals(value)) {
                            point += (int)questions.get("point");
                        }
                        if (Sanswer.equals("")) {
                            Sanswer = "" + value;
                        } else {
                            Sanswer = Sanswer + "," + value;
                        }
                        n++;
                        sn++;
                        break;
                    } else {
                        if (sn != 0) {
                            Sanswer = Sanswer + "," + " ";
                        }
                        n++;
                        sn++;
                    }
                }
            }
            //多选题可能漏选为空
            if (n > (int)testpapers.get("singlenum") && n <= ((int)testpapers.get("multiplenum") + (int)testpapers.get("singlenum"))) {
                if (!mf) {
                    mf = true;
                    continue;
                }
                for (; mn < (int)testpapers.get("multiplenum"); ) {
                    if ((int)questions.get("questionid") == (int)M.get(mn).get("questionid")) {
                        if (((String)questions.get("answer")).equals(value)) {
                            point += (int)questions.get("point");
                        }
                        if (Manswer.equals("")) {
                            Manswer = "" + value;
                        } else {
                            Manswer = Manswer + "," + value;
                        }
                        n++;
                        mn++;
                        break;
                    } else {
                        if (mn != 0) {
                            Manswer = Manswer + "," + " ";
                        }
                        n++;
                        mn++;
                    }
                }
            }
            if ( n > ((int)testpapers.get("multiplenum")+ (int)testpapers.get("singlenum")) && n <= ((int)testpapers.get("multiplenum") + (int)testpapers.get("singlenum") + (int)testpapers.get("judgenum"))) {
                if (!jf) {
                    jf = true;
                    continue;
                }
                for (; jn < (int)testpapers.get("judgenum"); ) {
                    if ((int)questions.get("questionid") == (int)J.get(jn).get("questionid")) {
                        boolean v;
                        if (value.equals("1")) {
                            v = true;
                        }else{
                            v = false;
                        }
                        if ((Boolean) questions.get("judgeanswer") == v) {
                            point += (int)questions.get("point");
                        }
                        if (Janswer.equals("")) {
                            Janswer = "" + value;
                        } else {
                            Janswer = Janswer + "," + value;
                        }
                        n++;
                        jn++;
                        break;
                    } else {
                        if (jn != 0) {
                            Janswer = Janswer + "," + " ";
                        }
                        n++;
                        jn++;
                    }
                }
            }
        }
        String yanswer = Sanswer + "," + Manswer + "," + Janswer;
        scores.setYanswer(yanswer);
        scores.setScore(point);
        scores.setReachtime(new Date());
        scoresService.updateScores(scores);
        return "redirect:/student/notfinishexam.html";
    }
}

